package com.zhou.cloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhou.cloud.entry.DemoHttpConst;
import com.zhou.cloud.entry.DemoHttpRespStatus;
import com.zhou.cloud.service.IDistributedLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @descrition: 分布式锁提供
 * @author: zhouyongjun
 * @date: 2022/11/23
 **/
@RestController
@RequestMapping("lock")
public class DistributedLockConroller {
    @Autowired
    @Qualifier("redisDistributedLockService")
    IDistributedLockService lockService;

    @PostMapping("/redis/try")
    public JSONObject tryLockFromRedis(String lockKey, String requestId, int expireMillis) {
        JSONObject jsonObject = new JSONObject();
        if (lockService.tryLock(lockKey,requestId,TimeUnit.MILLISECONDS,expireMillis))
        {
            jsonObject.put(DemoHttpConst.RESP_CODE, DemoHttpRespStatus.OK);
        }else {
            jsonObject.put(DemoHttpConst.RESP_CODE, DemoHttpRespStatus.FAIL);
        }

        return jsonObject;
    }

    @DeleteMapping("/redis/release/{lockKey}/{requestId}")
    public void releaseFromRedis(@PathVariable("lockKey") String lockKey, @PathVariable("requestId")String requestId) {
        JSONObject jsonObject = new JSONObject();
        lockService.releaseLock(lockKey,requestId);
    }
}
